<template>
	<el-button plain type="primary" @click="openDialog">新增</el-button>

	<el-table :data="tableData" border class="m-t-10px">
		<el-table-column type="index" align="center" label="#"></el-table-column>
		<el-table-column prop="id" label="ID" width="180" />
		<el-table-column prop="schoolName" label="学校名称" width="180" />
		<el-table-column prop="title" label="简章标题" width="180" />
		<el-table-column prop="attachments" label="附件列表" width="180" />
		<el-table-column prop="coverImage" label="封面图片" width="180" />
		<el-table-column prop="publishDate" label="官方发布时间" width="180">
			<template #default="scope">
				{{ moment(scope.row.publishDate).format("YYYY-MM-DD HH:mm:ss") }}
			</template>
		</el-table-column>
		<el-table-column prop="createdAt" label="创建时间" width="180">
			<template #default="scope">
				{{ moment(scope.row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}
			</template>
		</el-table-column>
		<el-table-column prop="createdAt" label="更新时间" width="180">
			<template #default="scope">
				{{ moment(scope.row.updatedAt).format("YYYY-MM-DD HH:mm:ss") }}
			</template>
		</el-table-column>
		<el-table-column fixed="right" label="操作" min-width="120">
			<template #default="scope">
				<!-- <el-button link type="primary"  @click="handleAssignRole(scope.row)"> 分配角色 </el-button> -->
				<el-button link type="primary" @click="edit(scope.row)">编辑</el-button>
				<el-button link type="primary" @click="del(scope.row)"> 删除 </el-button>
			</template>
		</el-table-column>
	</el-table>

	<el-dialog
		v-model="dialogFormVisible"
		:title="formData.id ? '编辑信息' : '添加信息'"
		width="70%"
		:before-close="beforeClose"
	>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="beforeClose">取消</el-button>
				<el-button @click="handleSubmit" type="primary">确认</el-button>
			</div>
		</template>
		<dynamic-form ref="dformRef" :schemas="schemas" :rules="rules" v-model:formData="formData">
			<template #content>
				<div style="width: 100%; border: 1px solid #cccccc">
					<!-- 工具栏 -->
					<Toolbar
						style="border-bottom: 1px solid #cccccc"
						:editor="editorRef"
						:defaultConfig="toolbarConfig"
						mode="default"
					/>
					<!-- 编辑器 -->
					<Editor
						style="width: 100%; height: 500px"
						v-model="valueHtml"
						:defaultConfig="editorConfig"
						mode="default"
						@onCreated="handleCreated"
					/>
				</div>
			</template>
			<template #coverImage>
				<el-upload ref="upload" v-model:file-list="coverFileList" :limit="1" :auto-upload="false">
					<template #trigger>
						<el-button type="primary">选择图片</el-button>
					</template>
					<el-button class="ml-3" type="success">上传图片 </el-button>
					<template #tip>
						<div class="el-upload__tip text-red">最多上传一张图片</div>
					</template>
				</el-upload>
			</template>
		</dynamic-form>
	</el-dialog>
</template>

<script setup lang="ts">
import { IGuideList, IGuide } from "@/api/guide/type";
import { FormSchema } from "@/components/DynamicForm/type";
import type { FormRules, UploadFile } from "element-plus";

import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IToolbarConfig } from "@wangeditor/editor";

import { getList, addGuide, updateGuide, delGuide } from "@/api/guide";
import moment from "moment";

const toolbarConfig: Partial<IToolbarConfig> = {
	/* 工具栏配置 */
};
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const editorConfig = { placeholder: "请输入内容..." };

const handleCreated = (editor) => {
	editorRef.value = editor; // 记录 editor 实例，重要！
};

const dialogFormVisible = ref(false);
/** 打开对话框 */
const openDialog = () => {
	dialogFormVisible.value = true;
};

/**表格数据 */
const tableData = ref<IGuideList>([]);

const init = async () => {
	const res = await getList({
		page: 1,
		pageSize: 20,
	});
	if (res.code === 200) {
		tableData.value = res.data.records;
	}
};

onMounted(async () => {
	init();
});

/**点击编辑按钮触发 */
const edit = async (row) => {
	openDialog();
	// 回显表单数据中的角色信息
	nextTick(() => {
		Object.keys(formData).forEach((Key) => {
			formData[Key] = row[Key];
		});
		valueHtml.value = row.content;
	});
};

/** 删除用户操作 */
const del = async (row: { id: number }) => {
	try {
		await ElMessageBox.confirm("确定删除该用户吗？", "警告", { type: "warning" });

		// 调用删除接口
		await delGuide(row.id);

		// 提示成功
		ElMessage.success("删除成功");

		// 刷新表格
		await init();
	} catch (err) {
		// 判断是否是用户取消操作
		if (err === "cancel" || err === "close") {
			ElMessage.info("取消删除");
		} else {
			console.error("删除失败", err);
			ElMessage.error("删除失败，请重试");
		}
	}
};

/**关闭弹窗之前调用 */
const beforeClose = () => {
	resetForm();
	//关闭弹窗
	dialogFormVisible.value = false;
};

const dformRef = ref();
/**重置数据 */
const resetForm = () => {
	formData.id = 0;
	dformRef.value.resetFields();
	editorRef.value.clear();
};
// 封面图片列表
const coverFileList = ref<UploadFile[]>([]);

// 富文本图片列表
const contentFileList = ref<UploadFile[]>([]);
/** 提交表单 */
const handleSubmit = async () => {
	if (!dformRef.value) return;

	try {
		// 1. 校验表单
		await dformRef.value.validate();

		// 2. 准备 FormData
		const fd = new FormData();

		// 文本字段
		const submitData = { ...formData, content: valueHtml.value };
		Object.entries(submitData).forEach(([key, value]) => {
			if (value !== undefined && value !== null) {
				fd.append(key, value as string);
			}
		});
		// 文件字段：封面
		if (coverFileList.value.length > 0) {
			fd.append("coverImage", coverFileList.value[0].raw as Blob);
		}

		// 文件字段：富文本图片
		// contentFileList.value.forEach((file) => {
		// 	fd.append("contentImages", file.raw);
		// });

		// 3. 根据是否有 id 判断新增/修改
		if (formData.id) {
			fd.append("id", formData.id.toString());
			await updateGuide(fd);
			ElMessage.success("修改成功");
		} else {
			await addGuide(fd);
			ElMessage.success("添加成功");
		}

		// 4. 关闭弹窗并重置表单
		dialogFormVisible.value = false;
		resetForm();

		// 5. 刷新表格
		await init();
	} catch (err) {
		console.log("表单校验失败或提交错误", err);
		ElMessage.error("操作失败，请检查表单内容");
	}
};

/**表单数据 */
const formData = reactive<IGuide>({
	id: 0,
	schoolName: "",
	title: "",
	summary: "",
	slug: "",
	content: "",
	coverImage: "",
	publishDate: "",
});
const valueHtml = ref("");

/**表单结构配置 */
const schemas: FormSchema[] = reactive([
	{
		field: "schoolName",
		label: "学校名称",
		component: "Input",
	},
	{
		field: "title",
		label: "标题",
		component: "Input",
	},
	{
		field: "summary",
		label: "摘要信息",
		component: "Input",
	},
	{
		field: "slug",
		label: "唯一标识符",
		component: "Input",
	},
	{
		field: "coverImage",
		label: "封面图片",
		component: "Custom",
		slot: "coverImage",
	},
	{
		field: "publishDate",
		label: "发布时间",
		component: "DatePicker",
		componentProps: { multiple: true },
		options: [
			{ label: "正常", value: 1 },
			{ label: "停用", value: 0 },
		],
	},
	{
		field: "content",
		label: "正文",
		component: "Custom",
		slot: "content",
		colProps: { span: 24 },
	},
]);

/**表单校验规则 */
const rules = reactive<FormRules<IGuide>>({
	schoolName: [
		{ required: true, message: "请输入学校名称", trigger: "blur" },
		{ min: 3, max: 15, message: "Length should be 3 to 5", trigger: "blur" },
	],
	title: [
		{
			required: true,
			message: "请输入招生简章标题",
			trigger: "blur",
		},
	],
});
</script>
